#include "plugin_helloworld.h"
#include <qdebug.h>
#include <qmessagebox.h>
#include "ajson5.h"
#include <fstream>

using std::ifstream;
using std::string;
using namespace ArduinoJson;

ARSSEXTERN ARSSPluginInterface* classFactory(ARSSAppInterface* appi)
{
	qDebug() << "plugin_helloworld classFactory()";
	return new PluginHelloWorld(appi);
}

void PluginHelloWorld::initGui()
{
	_appi->log("helloworld initGui");
	string pluginsDir = _appi->getPluginsDir();
	string currPluginDir = pluginsDir + "/helloworld";
	string iconfilename = currPluginDir + "/icon.png";
	string metafilename = currPluginDir + "/metadata.json";
	string displayName;
	string tabName;
	string groupName;
	{
		ifstream ifs(metafilename.c_str());
		DynamicJsonBuffer buffer;
		JsonObject& root = buffer.parse(ifs);
		displayName = root["display_name"].as<char*>();
		tabName = root["tab"].as<char*>();
		groupName = root["group"].as<char*>();
	}
	QPixmap pm(iconfilename.c_str());
	QAction* action = new QAction(QIcon(pm), displayName.c_str() );
	_action = action;
	QObject::connect(action, &QAction::triggered, this, &PluginHelloWorld::onActionTriggered);
	_appi->addPluginToRibbon(tabName.c_str(), groupName.c_str(), action);


}

void PluginHelloWorld::unload()
{
	_appi->log("helloworld unload");
}

void PluginHelloWorld::onActionTriggered()
{
	_appi->log("helloworld triggered");
	if (_widget == nullptr) {
		_widget = new QWidget(_appi->getRootWidget());
		Ui::Form ui;
		ui.setupUi(_widget);
		_appi->addPluginDockWidget(_widget, "HelloWorld", Qt::DockWidgetArea::RightDockWidgetArea);
	}
	else {
		bool vis = _widget->parentWidget()->isVisible();
		_widget->parentWidget()->setVisible(!vis);
	}
	

}